﻿using Fishing.Abstractions;
using Fishing.Common;
using Fishing.Core;
using Fishing.Properties;
using Fishing.View;
using Fishing.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Threading;
using System.Windows;

namespace Fishing
{
    public partial class App : Application
    {
        private readonly IServiceProvider _serviceProvider;

        public static IServiceProvider Services
        {
            get
            {
                return ((App)Current)._serviceProvider ?? throw new InvalidOperationException("尚未初始化服务提供程序");
            }
        }

        public App()
        {
            _serviceProvider = ConfigureServices();
        }

        private static IServiceProvider ConfigureServices()
        {
            return new ServiceCollection()
                .AddSingleton<MainWindow>()
                .AddSingleton<IDesktopCore, DesktopCore>()
                .AddSingleton<IThreadRipper, ThreadRipper>()
                .AddSingleton<KeyBoardHookService>()
                .AddSingleton<WndProcMsgWindow>()
                .AddSingleton<SettingsViewModel>()
                .AddSingleton<TaskbarIconViewModel>()
                .AddSingleton<ISettingsService, SettingsService>()
                .AddSingleton<IKeyBoardHookService, KeyBoardHookService>()
                .AddSingleton<IViewProvider, ViewProvider>()
                .AddSingleton<IProgramController, ProgramController>()
                .AddSingleton<ITaskbarIconService, TaskbarIconService>()

                .AddTransient<UpdaterViewModel>()

                .BuildServiceProvider();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                Directory.CreateDirectory(Constants.AppDataDir);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "AppData Directory Initialize Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Current.Shutdown();
            }

            MonitorHelper.Initialize();

            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            Services.GetRequiredService<ITaskbarIconService>().ShowBalloonTip(Lang.TextBalloonTitle, Lang.TextBalloonMessage, Images.favicon);

            var mainWnd = Services.GetRequiredService<MainWindow>();
            Current.MainWindow = mainWnd;

            mainWnd.Show();

            Services.GetRequiredService<WndProcMsgWindow>().Show();

            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            ((ServiceProvider)Services)?.Dispose();

            base.OnExit(e);
        }
    }
}
